using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ExpertPdf.HtmlToPdf;

namespace HtmlConvertAppDemo
{
    public partial class HtmlConvertForm : Form
    {
        public HtmlConvertForm()
        {
            InitializeComponent();
        }

        private void LoadImageFormats()
        {
            string[] imageFormats = Enum.GetNames(typeof(RenderImageFormat));
            ddlImageFormat.DataSource = imageFormats;
            ddlImageFormat.SelectedItem = RenderImageFormat.Jpeg.ToString();
        }

        private void LoadCompressionLevels()
        {
            string[] pdfCompressionLevels = Enum.GetNames(typeof(PdfCompressionLevel));
            ddlCompression.DataSource = pdfCompressionLevels;
            ddlCompression.SelectedItem = PdfCompressionLevel.Normal.ToString();
        }

        private void LoadPDFFormats()
        {
            string[] pdfFormats = Enum.GetNames(typeof(PdfPageSize));
            ddlPageFormat.DataSource = pdfFormats;
            ddlPageFormat.SelectedItem = PdfPageSize.A4.ToString();
        }

        private void LoadPageOrientations()
        {
            string[] pdfPageOrientations = Enum.GetNames(typeof(PDFPageOrientation));
            ddlPageOrientation.DataSource = pdfPageOrientations;
            ddlPageOrientation.SelectedItem = PDFPageOrientation.Portrait.ToString();
        }

        private string[] pdfStandards = { "PDF", "PDF/A", "PDF/X", "PDF/SigQA", "PDF/SigQB" };
        private PdfStandardSubset GetPdfStandard(string standardName)
        {
            switch (standardName)
            {
                case "PDF":
                    return PdfStandardSubset.Full;
                case "PDF/A":
                    return PdfStandardSubset.Pdf_A_1b;
                case "PDF/X":
                    return PdfStandardSubset.Pdf_X_1a;
                case "PDF/SigQA":
                    return PdfStandardSubset.Pdf_SiqQ_a;
                case "PDF/SigQB":
                    return PdfStandardSubset.Pdf_SiqQ_b;
                default:
                    return PdfStandardSubset.Full;

            }
        }

        private void LoadPdfSubsets()
        {
            ddlPdfSubset.DataSource = pdfStandards;
            ddlPdfSubset.SelectedItem = "PDF";
        }

        private void LoadTextAlignment()
        {
            string[] headerTextAlignments = Enum.GetNames(typeof(HorizontalTextAlign));
            ddlTitleAlign.DataSource = headerTextAlignments;
            ddlTitleAlign.SelectedItem = HorizontalTextAlign.Center.ToString();
        }

        private void LoadColors()
        {
            string[] colors = Enum.GetNames(typeof(KnownColor));

            ddlHeaderBackColor.DataSource = colors;
            ddlHeaderBackColor.SelectedItem = KnownColor.White.ToString();

            string[] colors2 = Enum.GetNames(typeof(KnownColor));
            ddlHeaderTextColor.DataSource = colors2;
            ddlHeaderTextColor.SelectedItem = KnownColor.Black.ToString();

            string[] colors3 = Enum.GetNames(typeof(KnownColor));
            ddlSubtitleColor.DataSource = colors3;
            ddlSubtitleColor.SelectedItem = KnownColor.Black.ToString();

            string[] colors4 = Enum.GetNames(typeof(KnownColor));
            ddlFooterColor.DataSource = colors4;
            ddlFooterColor.SelectedItem = KnownColor.Black.ToString();

            string[] colors5 = Enum.GetNames(typeof(KnownColor));
            ddlPageNumberTextColor.DataSource = colors5;
            ddlPageNumberTextColor.SelectedItem = KnownColor.Black.ToString();

            string[] colors6 = Enum.GetNames(typeof(KnownColor));
            ddlFooterBackColor.DataSource = colors6;
            ddlFooterBackColor.SelectedItem = KnownColor.White.ToString();
        }

        private void LoadFontTypes()
        {
            string[] windowsFontNames = new string[]
                    {
                        "Arial",
                        "Comic Sans MS",
                        "Courier New",
                        "Georgia",
                        "Impact",
                        "Lucida Console",
                        "Lucida Sans Unicode",
                        "Microsoft Sans Serif",
                        "Palatino Linotype",
                        "Symbol",
                        "Tahoma",
                        "Times New Roman",
                        "Trebuchet MS",
                        "Verdana",
                        "Webdings",
                        "WingDings"
                    };


            //string[] colors = Enum.GetNames(typeof(PdfFontType));
            ddlHeaderFont.DataSource = (string[])windowsFontNames.Clone(); ;
            ddlHeaderFont.SelectedItem = "Times New Roman";

            //string[] colors2 = Enum.GetNames(typeof(PdfFontType));
            ddlSubtitleFont.DataSource = (string[])windowsFontNames.Clone();
            ddlSubtitleFont.SelectedItem = "Times New Roman";

            //string[] colors3 = Enum.GetNames(typeof(PdfFontType));
            ddlFooterTextFont.DataSource = (string[])windowsFontNames.Clone(); ;
            ddlFooterTextFont.SelectedItem = "Times New Roman";

            //string[] colors4 = Enum.GetNames(typeof(PdfFontType));
            ddlPageNumberTextFont.DataSource = (string[])windowsFontNames.Clone(); ;
            ddlPageNumberTextFont.SelectedItem = "Times New Roman";
        }

        private bool PageIsValid()
        {
            errorProvider.Clear();
            bool invalid = false;

            if (textBoxWebPageURL.Text.Trim() == String.Empty)
            {
                errorProvider.SetError(textBoxWebPageURL, "The web page URL cannot be empty");
                invalid = true;
            }
            if (pnlSettingsPanel.Visible)
            {
                if (radioButtonCustomSize.Checked)
                {
                    // check custom width and height
                    try
                    {
                        int width = int.Parse(textBoxWebPageWidth.Text.Trim());
                        if (width < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxWebPageWidth, "The web page width must be a positive integer");
                        invalid = true;
                    }

                    try
                    {
                        int height = int.Parse(textBoxWebPageHeight.Text.Trim());
                        if (height < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxWebPageHeight, "The web page height must be a positive integer");
                        invalid = true;
                    }

                    try
                    {
                        int conversionDelay = int.Parse(textBoxConversionDelay.Text.Trim());
                        if (conversionDelay < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxConversionDelay, "The conversion delay must be a positive integer");
                        invalid = true;
                    }
                }

                if (radioConvertToPDF.Checked || radioButtonConvertToPDFSelectable.Checked)
                {
                    try
                    {
                        int leftMargin = int.Parse(textBoxLeftMargin.Text.Trim());
                        if (leftMargin < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxLeftMargin, "The PDF document left margin must be a positive integer");
                        invalid = true;
                    }

                    try
                    {
                        int rightMargin = int.Parse(textBoxRightMargin.Text.Trim());
                        if (rightMargin < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxRightMargin, "The PDF document right margin must be a positive integer");
                        invalid = true;
                    }

                    try
                    {
                        int topMargin = int.Parse(textBoxTopMargin.Text.Trim());
                        if (topMargin < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxTopMargin, "The PDF document top margin must be a positive integer");
                        invalid = true;
                    }

                    try
                    {
                        int bottomMargin = int.Parse(textBoxBottomMargin.Text.Trim());
                        if (bottomMargin < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxBottomMargin, "The PDF document bottom margin must be a positive integer");
                        invalid = true;
                    }

                    try
                    {
                        float headerTextFontSize = float.Parse(textBoxHeaderTextFontSize.Text.Trim());
                        if (headerTextFontSize < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxHeaderTextFontSize, "The PDF document header text font size must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float titleYLocation = float.Parse(textBoxTitleYLocation.Text.Trim());
                        if (titleYLocation < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxTitleYLocation, "The PDF document header title Y location must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float subtitleFontSize = float.Parse(textBoxSubtitleFontSize.Text.Trim());
                        if (subtitleFontSize < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxSubtitleFontSize, "The PDF document subtitle text font size must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float subtitleYSpacing = float.Parse(textBoxSubtitleYSpacing.Text.Trim());
                        if (subtitleYSpacing < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxSubtitleYSpacing, "The PDF document header title subtitle Y spacing must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float headerImageXLocation = float.Parse(textBoxHeaderImageXLocation.Text.Trim());
                        if (headerImageXLocation < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxHeaderImageXLocation, "The PDF document header image X location must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float headerImageYLocation = float.Parse(textBoxHeaderImageYLocation.Text.Trim());
                        if (headerImageYLocation < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxHeaderImageYLocation, "The PDF document header image Y location must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float footerTextFontSize = float.Parse(textBoxFooterTextFontSize.Text.Trim());
                        if (footerTextFontSize < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxFooterTextFontSize, "The PDF document footer text font size must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float pageNumberTextFontSize = float.Parse(textBoxPageNumberFontSize.Text.Trim());
                        if (pageNumberTextFontSize < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxPageNumberFontSize, "The PDF document footer page number text font size must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float headerHeight = float.Parse(textBoxHeaderHeight.Text.Trim());
                        if (headerHeight < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxHeaderHeight, "The PDF document header height must be a positive float");
                        invalid = true;
                    }

                    try
                    {
                        float footerHeight = float.Parse(textBoxFooterHeight.Text.Trim());
                        if (footerHeight < 0)
                            throw new Exception();
                    }
                    catch
                    {
                        errorProvider.SetError(textBoxFooterHeight, "The PDF document footer height must be a positive float");
                        invalid = true;
                    }
                }

            }
            return !invalid;
        }

        private void lnkBtnSettings_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!PageIsValid())
                return;

            if (pnlSettingsPanel.Visible)
            {
                pnlSettingsPanel.Visible = false;
                lnkBtnSettings.Text = "More Converter Settings >>";
            }
            else
            {
                pnlSettingsPanel.Visible = true;
                lnkBtnSettings.Text = "<< Hide Settings";
            }
            this.ClientSize = new Size(this.ClientSize.Width, pnlHeader.Height + pnlContent.Height + pnlConvertCommand.Height);
        }

        private void radioButtonAutodetect_CheckedChanged(object sender, EventArgs e)
        {
            pnlWebPageSize.Visible = !((RadioButton)sender).Checked;
            this.ClientSize = new Size(this.ClientSize.Width, pnlHeader.Height + pnlContent.Height + pnlConvertCommand.Height);
        }

        private void radioConvertToPDF_CheckedChanged(object sender, EventArgs e)
        {
            pnlPDFSettings.Visible = ((RadioButton)sender).Checked;
            pnlImgeOptions.Visible = !((RadioButton)sender).Checked;
            this.ClientSize = new Size(this.ClientSize.Width, pnlHeader.Height + pnlContent.Height + pnlConvertCommand.Height);
            cbGenerateSelectableText.Checked = false;
            //cbRTLEnabled.Visible =  cbLiveLinks.Visible = cbBookmarks.Visible = cbFitWidth.Visible = radioButtonConvertToPDFSelectable.Checked;
        }

        private void cbShowHeader_CheckedChanged(object sender, EventArgs e)
        {
            pnlHeaderOptions.Visible = ((CheckBox)sender).Checked;
            this.ClientSize = new Size(this.ClientSize.Width, pnlHeader.Height + pnlContent.Height + pnlConvertCommand.Height);
        }

        private void cbShowFooter_CheckedChanged(object sender, EventArgs e)
        {
            pnlFooterOptions.Visible = ((CheckBox)sender).Checked;
            this.ClientSize = new Size(this.ClientSize.Width, pnlHeader.Height + pnlContent.Height + pnlConvertCommand.Height);
        }

        private void HtmlConvertForm_Load(object sender, EventArgs e)
        {
            LoadImageFormats();
            LoadPDFFormats();
            LoadPageOrientations();
            LoadColors();
            LoadTextAlignment();
            LoadFontTypes();
            LoadCompressionLevels();
            LoadPdfSubsets();
        }

        private PdfConverter GetPDFConverter()
        {

            // get the HTML document width and height in pixels
            // default HTML document width is 1024 pixels
            int pageWidthPx = 0;
            int pageHeightPx = 0;

            // set common properties
            if (!radioButtonAutodetect.Checked)
            {
                pageWidthPx = int.Parse(textBoxWebPageWidth.Text.Trim());
                pageHeightPx = int.Parse(textBoxWebPageHeight.Text.Trim());
            }

            // create the PDF converter
            PdfConverter pdfConverter = new PdfConverter(pageWidthPx, pageHeightPx);

            //pdfConverter.LicenseKey = "put your license key here";

            // generate a PDF with selectable text or a PDF with an embedded image
            pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = cbGenerateSelectableText.Checked;

            // set PDF page size
            PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), ddlPageFormat.SelectedItem.ToString());
            pdfConverter.PdfDocumentOptions.PdfPageSize = pageSize;
            if (pageSize == PdfPageSize.Custom)
            {
                // set custom PDF page size
                pdfConverter.PdfDocumentOptions.CustomPdfPageSize = new SizeF(float.Parse(textBoxCustomPdfPageWidth.Text.Trim()),
                            float.Parse(textBoxCustomPdfPageHeight.Text.Trim()));
            }
            // set the PDF page orientation (portrait or landscape)
            pdfConverter.PdfDocumentOptions.PdfPageOrientation = (PDFPageOrientation)Enum.Parse(typeof(PDFPageOrientation), ddlPageOrientation.SelectedItem.ToString());
            // set the compression level of the streams in the PDF document
            pdfConverter.PdfDocumentOptions.PdfCompressionLevel = (PdfCompressionLevel)Enum.Parse(typeof(PdfCompressionLevel), ddlCompression.SelectedItem.ToString());
            // the the PDF standard used to generate the PDF document (PDF, PDF/A, PDF/X or PDF/SigQ)
            pdfConverter.PdfStandardSubset = GetPdfStandard(ddlPdfSubset.SelectedItem.ToString());
            // show or hide header and footer
            pdfConverter.PdfDocumentOptions.ShowHeader = cbShowHeader.Checked;
            pdfConverter.PdfDocumentOptions.ShowFooter = cbShowFooter.Checked;
            //set PDF document margins
            pdfConverter.PdfDocumentOptions.LeftMargin = int.Parse(textBoxLeftMargin.Text.Trim());
            pdfConverter.PdfDocumentOptions.RightMargin = int.Parse(textBoxRightMargin.Text.Trim());
            pdfConverter.PdfDocumentOptions.TopMargin = int.Parse(textBoxTopMargin.Text.Trim());
            pdfConverter.PdfDocumentOptions.BottomMargin = int.Parse(textBoxBottomMargin.Text.Trim());

            // set if the fonts are embedded in the PDF document
            pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked;
            // set if the images are compressed with JPEG in PDF to reduce the PDF document size
            pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked;
            // set if the HTML content is resized if necessary to fit the PDF page width
            pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked;
            // set if the PDF page is automatically resized to show all the HTML content when FitWidth is false
            pdfConverter.PdfDocumentOptions.AutoSizePdfPage = cbAutoSizePdfPage.Checked;

            // set if the HTTP links are enabled in the generated PDF
            pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked;

            // set if the converter should try to avoid breaking the text between PDF pages - default is true
            pdfConverter.AvoidTextBreak = cbAvoidTextBreak.Checked;
            // set if the converter should try to avoid breaking the images between PDF pages - default is false
            pdfConverter.AvoidImageBreak = cbAvoidImageBreak.Checked;

            //enable JavaScripts and Java applets during conversion
            pdfConverter.ScriptsEnabled = pdfConverter.ScriptsEnabledInImage = cbScriptsEnabled.Checked;

            // enable ActiveX and flash during conversion
            pdfConverter.ActiveXEnabled = pdfConverter.ActiveXEnabledInImage = cbActiveXEnabled.Checked;

            // set a delay if necessary to allow asynchronous content like ActiveX controls to load before starting rendering
            pdfConverter.ConversionDelay = int.Parse(textBoxConversionDelay.Text.Trim());

            // set bookmarking options
            pdfConverter.PdfBookmarkOptions.TagNames = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null;

            // set server authentication if necessary
            if (textBoxUsername.Text.Trim().Length > 0)
            {
                pdfConverter.AuthenticationOptions.Username = textBoxUsername.Text.Trim();
                pdfConverter.AuthenticationOptions.Password = textBoxPassword.Text.Trim();
            }

            pdfConverter.PdfHeaderOptions.ShowOnFirstPage = cbShowHeaderOnFirstPage.Checked;
            pdfConverter.PdfHeaderOptions.ShowOnOddPages = cbShowHeaderOnOddPages.Checked;
            pdfConverter.PdfHeaderOptions.ShowOnEvenPages = cbShowHeaderOnEvenPages.Checked;
            pdfConverter.PdfHeaderOptions.HeaderBackColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlHeaderBackColor.SelectedItem.ToString()));
            pdfConverter.PdfHeaderOptions.HeaderHeight = float.Parse(textBoxHeaderHeight.Text.Trim());
            pdfConverter.PdfHeaderOptions.HeaderText = textBoxHeaderTitle.Text;
            pdfConverter.PdfHeaderOptions.HeaderTextAlign = (HorizontalTextAlign)Enum.Parse(typeof(HorizontalTextAlign), ddlTitleAlign.SelectedItem.ToString());
            pdfConverter.PdfHeaderOptions.HeaderTextColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlHeaderTextColor.SelectedItem.ToString()));
            pdfConverter.PdfHeaderOptions.HeaderTextFontSize = float.Parse(textBoxHeaderTextFontSize.Text.Trim());
            pdfConverter.PdfHeaderOptions.HeaderTextFontName = ddlHeaderFont.SelectedItem.ToString();
            pdfConverter.PdfHeaderOptions.HeaderTextFontStyle = FontStyle.Bold | FontStyle.Italic | FontStyle.Underline;
            pdfConverter.PdfHeaderOptions.HeaderTextYLocation = float.Parse(textBoxTitleYLocation.Text.Trim());
            pdfConverter.PdfHeaderOptions.HeaderSubtitleText = textBoxHeadeSubtitle.Text;
            pdfConverter.PdfHeaderOptions.HeaderSubtitleTextColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlSubtitleColor.SelectedItem.ToString()));
            pdfConverter.PdfHeaderOptions.HeaderSubtitleTextFontSize = float.Parse(textBoxSubtitleFontSize.Text.Trim());
            pdfConverter.PdfHeaderOptions.HeaderTitleSubtitleYSpacing = float.Parse(textBoxSubtitleYSpacing.Text.Trim());
            float imageXLocation = float.Parse(textBoxHeaderImageXLocation.Text.Trim());
            float imageyLocation = float.Parse(textBoxHeaderImageYLocation.Text.Trim());
            pdfConverter.PdfHeaderOptions.HeaderImageLocation = new PointF(imageXLocation, imageyLocation);
            if (textBoxHeaderImagePath.Text.Trim() != String.Empty)
            {
                pdfConverter.PdfHeaderOptions.HeaderImage = Image.FromFile(textBoxHeaderImagePath.Text.Trim());
            }
            pdfConverter.PdfHeaderOptions.DrawHeaderLine = cbDrawHeaderLine.Checked;

            pdfConverter.PdfFooterOptions.FooterText = textBoxFooterText.Text;
            pdfConverter.PdfFooterOptions.FooterBackColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlFooterBackColor.SelectedItem.ToString()));
            pdfConverter.PdfFooterOptions.FooterHeight = float.Parse(textBoxFooterHeight.Text.Trim());
            pdfConverter.PdfFooterOptions.FooterTextColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlFooterColor.SelectedItem.ToString()));
            pdfConverter.PdfFooterOptions.FooterTextFontName = ddlFooterTextFont.SelectedItem.ToString();
            pdfConverter.PdfFooterOptions.FooterTextFontSize = float.Parse(textBoxFooterTextFontSize.Text.Trim());
            pdfConverter.PdfFooterOptions.FooterTextWidth = float.Parse(textBoxFooterWidth.Text.Trim());
            pdfConverter.PdfFooterOptions.FooterTextYLocation = float.Parse(textBoxFooterTextYLocation.Text.Trim());
            pdfConverter.PdfFooterOptions.DrawFooterLine = cbDrawFooterLine.Checked;
            pdfConverter.PdfFooterOptions.PageNumberText = textBoxPageNumberText.Text;
            pdfConverter.PdfFooterOptions.PageNumberTextColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlPageNumberTextColor.SelectedItem.ToString()));
            pdfConverter.PdfFooterOptions.PageNumberTextFontName = ddlPageNumberTextFont.SelectedItem.ToString();
            pdfConverter.PdfFooterOptions.PageNumberTextFontSize = float.Parse(textBoxPageNumberFontSize.Text.Trim());
            pdfConverter.PdfFooterOptions.PageNumberYLocation = float.Parse(textBoxPageNumberYLocation.Text.Trim());
            pdfConverter.PdfFooterOptions.ShowPageNumber = cbShowPageNumber.Checked;
            pdfConverter.PdfHeaderOptions.ShowOnFirstPage = cbShowFooterOnFirstPage.Checked;
            pdfConverter.PdfFooterOptions.ShowOnEvenPages = cbShowFooterOnEvenPages.Checked;
            pdfConverter.PdfFooterOptions.ShowOnOddPages = cbShowFooterOnOddPages.Checked;

            return pdfConverter;
        }

        private ImgConverter GetImgConverter()
        {
            int pageWidth = 0;
            int pageHeight = 0;

            // set common properties
            if (!radioButtonAutodetect.Checked)
            {
                pageWidth = int.Parse(textBoxWebPageWidth.Text.Trim());
                pageHeight = int.Parse(textBoxWebPageHeight.Text.Trim());
            }

            // create the PDF converter
            ImgConverter imgConverter = new ImgConverter(pageWidth, pageHeight);

            // set server authentication if necessary
            if (textBoxUsername.Text.Trim().Length > 0)
            {
                imgConverter.AuthenticationUsername = textBoxUsername.Text.Trim();
                imgConverter.AuthenticationPassword = textBoxPassword.Text.Trim();
            }

            // enable JavaScript and ActiveX controls if necessary
            imgConverter.ScriptsEnabled = cbScriptsEnabled.Checked;
            imgConverter.ActiveXEnabled = cbActiveXEnabled.Checked;

            // set a delay if necessary to allow asynchronous content like ActiveX controls to load before starting rendering
            imgConverter.ConversionDelay = int.Parse(textBoxConversionDelay.Text.Trim());

            return imgConverter;
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            if (!PageIsValid())
                return;

            this.Cursor = Cursors.WaitCursor;

            string outFile = null;

            try
            {
                
                if (radioConvertToPDF.Checked || radioButtonConvertToPDFSelectable.Checked)
                {
                    PdfConverter pdfConverter = GetPDFConverter();

                    outFile = Path.Combine(Application.StartupPath, "RenderedPage.pdf");
                    try
                    {
                        pdfConverter.SavePdfFromUrlToFile(textBoxWebPageURL.Text, outFile);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }
                }
                else
                {
                    ImgConverter imgConverter = GetImgConverter();

                    outFile = Path.Combine(Application.StartupPath, String.Format("RenderedPage.{0}", ddlImageFormat.SelectedItem.ToString()));
                    try
                    {
                        RenderImageFormat renderImageFormat = (RenderImageFormat)Enum.Parse(typeof(RenderImageFormat), ddlImageFormat.SelectedItem.ToString());
                        imgConverter.SaveImageFromUrlToFile(
                                textBoxWebPageURL.Text,
                                RenderImageFormatConverter.GetImageFormat(renderImageFormat),
                                outFile
                             );
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }
                }
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }

            DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }

        private void radioButtonConvertToPDFSelectable_CheckedChanged(object sender, EventArgs e)
        {
            pnlPDFSettings.Visible = ((RadioButton)sender).Checked;
            pnlImgeOptions.Visible = !((RadioButton)sender).Checked;
            this.ClientSize = new Size(this.ClientSize.Width, pnlHeader.Height + pnlContent.Height + pnlConvertCommand.Height);
            cbGenerateSelectableText.Checked = true;
            //cbRTLEnabled.Visible = cbLiveLinks.Visible = cbBookmarks.Visible = cbFitWidth.Visible = radioButtonConvertToPDFSelectable.Checked;
        }

        private void btnChangeHeaderImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            DialogResult res = fd.ShowDialog();
            if (res == DialogResult.OK)
            {
                textBoxHeaderImagePath.Text = fd.FileName;
            }
        }

        private void radioConvertToImage_CheckedChanged(object sender, EventArgs e)
        {
            cbJpegCompression.Visible = cbLiveLinks.Visible = cbBookmarks.Visible = cbFitWidth.Visible = cbAutoSizePdfPage.Visible
                = cbEmbedFonts.Visible = cbJpegCompression.Visible = !radioConvertToImage.Checked;
        }
    }
}